﻿using AppManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace AppManager.DAL
{
    public class MessageDAL : BaseDAL<Message>
    {
        /// <summary>
        /// 就算
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Message> GetSendingList()
        {
            return (from m in Db.Current.Messages
                    where m.ExpirseDate > DateTime.Now
                    && ((from md in Db.Current.MessageDevices where m.Id == md.MessageId && !md.RemoteServerResult && md.FailSendCount <= 5 && !(md.SendResult && md.NextSendTime >= DateTime.Now) select md).Count()) > 0
                    select m).ToList().Take(100);

            //return (from m in Db.Current.Messages
            //        join d in Db.Current.MessageDevices on m.Id equals d.MessageId into dg
            //        join p in Db.Current.Projects on m.ProjectId equals p.Id into pg
            //        from p in pg.DefaultIfEmpty()
            //        where m.ExpirseDate > DateTime.Now
            //        && ((from md in Db.Current.MessageDevices where m.Id == md.MessageId && !md.RemoteServerResult && md.FailSendCount <= 5 && !(md.SendResult && md.NextSendTime >= DateTime.Now) select md).Count()) > 0
            //        select new { m, Devices = dg.ToList(), Project = p }).ToList().
            //        Select(s => { s.m.Devices = s.Devices; s.m.Project = s.Project; return s.m; });
            //這種方式非常垃圾,因為是一個無限的子查詢,雖然表面上和上面的方法差不多但應該只是說ef對這種查詢做了優化,應該是把很多的語句一次性執行完了,所以很快,但從原理上來講不應該使用這種方式吧
            //return (from m in Db.Current.Messages
            //        where m.ExpirseDate > DateTime.Now
            //        && ((from md in Db.Current.MessageDevices where m.Id == md.MessageId && !md.RemoteServerResult && md.FailSendCount <= 5 && !(md.SendResult && md.NextSendTime >= DateTime.Now) select md).Count()) > 0
            //        select m).ToList()
            //        .Select(s =>
            //        {
            //            s.Devices = (from md in Db.Current.MessageDevices where s.Id == md.MessageId select md).ToList();
            //            s.Project = (from p in Db.Current.Projects where s.ProjectId == p.Id select p).FirstOrDefault();
            //            return s;
            //        }).ToList();
        }

        public void BindList(Message message, List<MessageDevice> devices)
        {
            message.Devices = devices;
        }
    }
}
